package com.dy.dept.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dy.dept.entity.User;
import com.dy.dept.entity.Userrole;
import com.dy.dept.service.IUserService;
import com.dy.dept.service.IUserroleService;
import com.dy.dept.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Wrapper;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dy
 * @since 2022-03-27
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserroleService userroleService;

    @GetMapping("/login/{username}/{password}")
    public User login(@PathVariable("username")String username, @PathVariable("password")String password, HttpServletRequest request){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        wrapper.eq("user_pwd",password);
        User one = userService.getOne(wrapper);

        QueryWrapper<Userrole> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("fk_user_id",one.getUserId());
        List<Userrole> list = userroleService.list(wrapper1);

        HttpSession session = request.getSession();
        session.setAttribute("user",one);
        session.setAttribute("userrole",list);
        return one;
    }

    @PostMapping("/headphoto")
    public String addHead( @RequestParam("headName") MultipartFile file) throws IOException {
        return FileUtil.saveFile(file);
    }

    @PostMapping("/register")
    public boolean register(String username ,String password, String imgSrc) throws IOException {
        //判断用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        User one = userService.getOne(wrapper);
        if (one == null){
            User user = new User(null,username,password,imgSrc);
            boolean save = userService.save(user);
            return save;
        }else {
            return false;
        }
    }

    @PostMapping("/updatehead/{role}")
    public String updateHeadPhoto(@RequestParam("username")String username,@RequestParam("headFile")MultipartFile file) throws IOException {
        String s = FileUtil.saveFile(file);
        User user = new User();
        user.setUserHead(s);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        boolean update = userService.update(user, wrapper);
        if (update){
            return s;
        }else {
            return null;
        }
    }
}
